import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:vdrag_saas/bus.dart';
import 'package:vdrag_saas/config.dart';
import 'package:vdrag_saas/detail/custom_video_progress.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

class GvVideoPlayer extends StatefulWidget {
  String url;
  bool autoPlay;
  GlobalKey? globalKey;
  GvVideoPlayer(this.url, {required this.autoPlay, this.globalKey})
      : super(key: globalKey);

  @override
  GvVideoPlayerState createState() => GvVideoPlayerState();
}

class GvVideoPlayerState extends State<GvVideoPlayer> {
  late VideoPlayerController _controller;
  late ChewieController _chewieController;
  bool hasPause = false;
  @override
  void initState() {
    // 初始化视频控制器，这里仅以网络视频为例
    super.initState();
    _initControllers();
  }

  void play() {
    if (!_controller.value.isPlaying) {
      _controller.play();
    }
  }

  void pause() {
    if (_controller.value.isPlaying) {
      _controller.pause();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _chewieController.dispose();
    super.dispose();
  }
  void onPause() {
    hasPause = !_controller.value.isPlaying;
  }

  void _initControllers() {
    Uri url = Uri.parse(HttpConfig.baseUrl + widget.url);
    _controller = VideoPlayerController.networkUrl(url)
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        setState(() {
          if (widget.autoPlay && Global.fromHome) {
            _controller.play();
          }
        });
      })
      ..addListener(() {
        if (_controller.value.hasError) {
          print(_controller.value.errorDescription);
        }
      });
    _chewieController = ChewieController(
      customControls: MyMaterialControls(onPause),
      videoPlayerController: _controller,
      // autoPlay: true, // 自动播放
      looping: true, // 是否循环播放
      showControls: true, // 显示播放控制栏
      showOptions: false,
      useRootNavigator: false,
      materialProgressColors: ChewieProgressColors(
        playedColor: const Color(0xff2196F3),
        handleColor: const Color(0xff2196F3),
        backgroundColor: const Color(0x66dddddd),
        bufferedColor: const Color(0xffDDDDDD),
      ),
      errorBuilder: (context, errorMessage) {
        return Center(
          child: Text(errorMessage),
        );
      },
      // routePageBuilder: (context, animation, animation2, control) {
      //   return FullScreenVideo(_controller, _chewieController);
      // }
    );
  }

  @override
  Widget build(BuildContext context) {
    return _controller.value.isInitialized
        ? VisibilityDetector(
            key: ValueKey(widget.url),
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: Chewie(
                controller: _chewieController,
              ),
            ),
            onVisibilityChanged: (info) {
              if (_chewieController.isFullScreen) {
                return;
              }
              if (!mounted) {
                return;
              }
              if (hasPause) { // 如果已经手动暂停，请不要再自动播放
                return;
              }
              if (info.visibleFraction < 0.5) {
                _controller.pause();
              } else {
                if (Global.fromHome) {
                  _controller.play();
                }
              }
            })
        : Image.asset('assets/images/loading.gif', fit: BoxFit.fill);
  }
}
